/**
 * @description: 钉钉工具类
 * @version: 0.0.1
 * @author: xiech
 * @Date: 2023-06-26 16:16:07
 */

import { Provide, Inject } from '@midwayjs/core';
import { HttpService } from '@midwayjs/axios';
import { Config } from '@midwayjs/decorator';
import crypto = require('crypto');

@Provide()
export class DingTalkUtils {

  @Inject()
  httpService: HttpService;

  @Config('dingTalk')
  dingTalkConfig: any;

  // 钉钉报警机器人
  async dingdingRobot(webhook: any, form: object, signSEC = this.dingTalkConfig.signSEC || '') {
    // 签名处理
    if (signSEC) {
      const timestamp = new Date().getTime();
      const hmac = crypto.createHmac('sha256', signSEC);
      hmac.update(timestamp + '\n' + signSEC);
      const sign = encodeURIComponent(hmac.digest('base64'));
      webhook += `&sign=${sign}&timestamp=${timestamp}`;
    }
    const res = await this.httpService.post(webhook, JSON.stringify(form), { headers: { 'Content-Type': 'application/json' } });
    if (res && res.data && !res.data.errcode) {
      return { success: true, msg: "发送成功" };
    };
    return { success: false, msg: res.data.errmsg || "发送失败" };
  }
}